package com.jtech.together.mvp.presenter;

import android.content.Context;
import android.os.Bundle;

import com.jtech.together.manager.UserManager;
import com.jtech.together.model.TrendsModel;
import com.jtech.together.model.event.TrendsEvent;
import com.jtech.together.mvp.contract.TrendsContract;
import com.jtech.together.util.BmobUtil;
import com.jtech.together.util.Bus;

import java.util.Arrays;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.UpdateListener;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 动态
 * Created by wuxubaiyang on 2017/5/10.
 */
public class TrendsPresenter implements TrendsContract.Presenter {
    private Context context;
    private TrendsContract.View view;

    public TrendsPresenter(Context context, TrendsContract.View view, Bundle bundle) {
        this.context = context;
        this.view = view;
    }

    @Override
    public void loadTrends(int pageIndex, int displayNumber, final boolean loadMore) {
        new BmobQuery<TrendsModel>()
                .setLimit(displayNumber)
                .setSkip(pageIndex * displayNumber)
                .order("-createdAt")
                .include("user")
                .findObjectsObservable(TrendsModel.class)
                .subscribeOn(Schedulers.io())
                .map(new Func1<List<TrendsModel>, List<TrendsModel>>() {
                    @Override
                    public List<TrendsModel> call(List<TrendsModel> trendsModels) {
                        String myUserId = UserManager.getCurrentUserId();
                        for (int i = 0; i < trendsModels.size(); i++) {
                            //处理喜欢集合
                            for (String userId : trendsModels.get(i).getLikes()) {
                                if (myUserId.equals(userId)) {
                                    trendsModels.get(i).setLikes(Arrays.asList(myUserId));
                                    break;
                                }
                            }
                            //处理不喜欢人集合
                            for (String userId : trendsModels.get(i).getUnlikes()) {
                                if (myUserId.equals(userId)) {
                                    trendsModels.get(i).setUnlikes(Arrays.asList(myUserId));
                                    break;
                                }
                            }
                        }
                        return trendsModels;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<TrendsModel>>() {
                    @Override
                    public void call(List<TrendsModel> trendsModels) {
                        view.loadSuccess(trendsModels, loadMore);
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        view.loadFail("加载失败，请重试");
                    }
                });
    }

    @Override
    public void like(final TrendsModel trendsModel, final int count) {
        trendsModel.like(UserManager.getCurrentUser(), count);
        trendsModel.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (null == e) {
                    view.operationSuccess(trendsModel);
                    //发送消息
                    Bus.get().post(new TrendsEvent(trendsModel.getObjectId(), TrendsEvent.STATE_LIKE, count));
                } else {
                    view.operationFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                }
            }
        });
    }

    @Override
    public void unlike(final TrendsModel trendsModel, final int count) {
        trendsModel.unlike(UserManager.getCurrentUser(), count);
        trendsModel.update(new UpdateListener() {
            @Override
            public void done(BmobException e) {
                if (null == e) {
                    view.operationSuccess(trendsModel);
                    //发送消息
                    Bus.get().post(new TrendsEvent(trendsModel.getObjectId(), TrendsEvent.STATE_UNLIKE, count));
                } else {
                    view.operationFail(BmobUtil.getErrorMessage(e.getErrorCode()));
                }
            }
        });
    }
}